// 添加到本地存储
export function addProduct(item, next){
	// 当前存储购物车内产品的数组
	let cart = []
	if( typeof window !== "undefined" ) {
		// 当前localStorage有cart
		if(localStorage.getItem('cart')){
			cart = JSON.parse(localStorage.getItem('cart'))
		}
		// 当前localStorage没有cart,将添加的产品添加到cart数组中
		cart.push({
			...item,
			count: 1
		})
		console.log(cart);
		// 但是添加到购物车,相同的id值的产品必须是唯一的,只是数量的变化
		cart = Array.from(new Set(cart.map(item=>item._id))).map(id=>
			cart.find(product=>product._id === id)
		)
		localStorage.setItem('cart', JSON.stringify(cart))
		next && next()
	}
}

// 获取本地存储的数据
export function getProduct () {
	if(typeof window !== "undefined") {
		if(localStorage.getItem('cart')){
			return JSON.parse(localStorage.getItem('cart'))
		}
		return []
	}
}

// 改变当前产品的数量
export function updateProduct (itemId, count) {
	let cart = []
	if(typeof window !== 'undefined') {
		if(localStorage.getItem('cart')){
			cart = JSON.parse(localStorage.getItem('cart'))
			const target = cart.find(item=>item._id === itemId )
			target.count = count
			localStorage.setItem('cart', JSON.stringify(cart))
		}
	}
	return cart
}

// 删除当前选中的产品
export function deleteProduct (itemId) {
	let cart= []
	if(typeof window !== 'undefined') {
		if(localStorage.getItem('cart')){
			cart = JSON.parse(localStorage.getItem('cart'))
			const index =cart.findIndex(item=>item.id === itemId)
			cart.splice(index,1)
			localStorage.setItem('cart', JSON.stringify(cart))
		}
	}
	return cart
}

// 清除本地存储
export function emptyCart () {
	let cart = []
	if(typeof window !== 'undefined'){
		if(localStorage.getItem('cart')) {
			cart = JSON.parse(localStorage.getItem('cart'))
			cart = []
			JSON.stringify(localStorage.setItem('cart',cart))
		}
	}
}